<?php
/**
 * User: Drery
 * Date: 2015/12/28
 * Time: 10:16
 */

namespace backend\components;

use backend\models\Admin;
use common\models\Level;
use yii\filters\AccessRule;
use yii\web\ServerErrorHttpException;


class MultiLevelAccess extends AccessRule
{
    public function allows($action, $user, $request)
    {
        $controller = $action->controller;
        if (!method_exists($controller, 'getCurrentDistricts')) {
            throw new ServerErrorHttpException();
        }

        $ids = $controller->getCurrentDistricts();
        if (!$ids)
            throw new ServerErrorHttpException();

        /** @var Admin $admin */
        $admin = $user->identity;
        if ($admin->level == Level::HIGHEST)
            return true;

        $districtIds = $admin->getDistrictIds();

        foreach ($ids as $id) {
            if (!in_array($id, $districtIds))
                return false;
        }

        return true;
    }
}